package com.example.carrierapp.base

import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Bundle
import android.view.View
import com.example.carrierapp.ui.main.dispatch.detail.delivery.DispatchDeliveryContract
import com.example.carrierapp.ui.main.dispatch.detail.delivery.DispatchDeliveryPresenter
import com.example.lb.fingerdemo.BR
import java.lang.reflect.ParameterizedType


abstract class DatabindingFragment<M, V, P : BasePresenter<V>> : MVPBaseFragment<V, P>() {
    open var model: M = getClassInstance().newInstance()
    private val binding by lazy { mRootView?.let { DataBindingUtil.bind<ViewDataBinding>(it) } }

    private fun initDatabinding() {
        binding?.setVariable(BR.model, model)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        initDatabinding()
        super.onViewCreated(view, savedInstanceState)
    }

    fun notifyModel(tempModel: M) {
        model = tempModel
        binding?.setVariable(BR.model, tempModel)
        binding?.executePendingBindings()
    }

    /**
     * 获取泛型class对象
     * @param index 多个泛型时泛型索引，取第几个泛型
     */
    open fun getClassInstance(index: Int = 0): Class<M> {
        val type = javaClass.genericSuperclass
        // 判断 是否泛型
        return if (type is ParameterizedType) {
            // 返回表示此类型实际类型参数的Type对象的数组.
            // 当有多个泛型类时，数组的长度就不是1了
            val ptype = type.actualTypeArguments
            ptype[index] as Class<M>  //将第一个泛型T对应的类返回
        } else {
            Any::class.java as Class<M>//若没有给定泛型，则返回Object类
        }
    }
}
